package com.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.base.constant.MediaTypeMore;
import com.base.util.BaseIOUtils;
import com.base.util.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;

public class FileController extends BaseController{

	@Value("${file.saveLocation}")
	private String saveFileLocation;

	@RequestMapping("/download")
	public ResponseEntity<byte[]> download(String id) throws Exception {
		File file = new File(saveFileLocation+"/"+id);
		if (!file.exists()) {
			throw new FileNotFoundException("文件飞了。。。。");
		}
		HttpHeaders headers = new HttpHeaders();
		String fileName = new String(file.getName().getBytes("UTF-8"),
				"iso-8859-1");// 为了解决中文名称乱码问题
		if(fileName.toUpperCase().endsWith(".MP3")){
			headers.setContentType(MediaType.parseMediaType(MediaTypeMore.MP3TYPE));
			headers.setContentLength(file.length());
		}else{
			headers.setContentDispositionFormData("attachment", fileName);
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		}
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
	}

	@RequestMapping("/resource")
	public void resource(String id) throws Exception {
		File file = new File(saveFileLocation+"/"+id);
		if (!file.exists()) {
			throw new FileNotFoundException("文件飞了。。。。");
		}
		String fileName = new String(file.getName().getBytes("UTF-8"),
				"iso-8859-1");// 为了解决中文名称乱码问题
		response.setContentLength((int)file.length());
		response.setHeader("attachment",fileName);
		response.setHeader("Accept-Ranges","bytes");
		if(fileName.toUpperCase().endsWith(".MP3")){
			response.setContentType(MediaTypeMore.MP3TYPE);
		}
		BaseIOUtils.copyFromStream(new FileInputStream(file),response.getOutputStream());
	}
	
}
